package controllers;

import play.Play;
import play.Logger;
import play.mvc.*;
import net.solosky.maplefetion.*;
import net.solosky.maplefetion.bean.*;
import net.solosky.maplefetion.client.*;
import net.solosky.maplefetion.event.*;
import net.solosky.maplefetion.event.action.*;
import net.solosky.maplefetion.net.*;
import net.solosky.maplefetion.event.action.success.*;
import java.io.*;
import java.util.*;

public class Fetions extends Application {
  
    public static final String SEPARATOR = "/__mytusi_sm_split__/";
  
    public static void show(String mobile) {
        Logger.debug("show : " + mobile);     
        Logger.debug("request :" + request.toString()); 
        render(mobile);
    }
    
    // 发送内容
    public static void sendSm(String mobile, String password, String content,String destMobile, String verifyImgId,String verifyCode) {
        Logger.debug("0. url is " + request.url);
        debugParams();
        Logger.debug("2. 准备从" + mobile + "发送短信至");
        if(isBlank(content)) {
            Logger.debug("3. content_requested");
            renderArgs.put("state","content_requested"); 
            renderArgs.put("message","短信内容必填");
            //invalidXml("content_requested");
        }
        validateStateAndDoIt(mobile, password, content, destMobile,  verifyImgId, verifyCode, "sending");
        renderTemplate("/Fetions/sendSm.xml"); 
    }
    
    // 取得验证码
    public static void getVerify(String mobile) {
        try {
            Logger.debug("mobile is : " + mobile);
            FetionClient client = new FetionClient(mobile,"");  
            /*LoginState state = null;
            while (state != LoginState.SSI_NEED_VERIFY && state != LoginState.SSI_VERIFY_FAIL) {
                state = client.syncLogin();
                Logger.debug(" state is " + state);
            }*/
            VerifyImage vImg = makeVerfiy(client);
            renderArgs.put("state","success");
            renderArgs.put("verifyImgId",vImg.getImageId());
            renderArgs.put("verifyImgFileName",verifyImageFileName(vImg));            
            renderArgs.put("message","成功获取验证码图片");
        } catch(IOException ioe) {
            Logger.error("创建验证码失败(IOException)：",ioe);
            renderArgs.put("message",ioe.getMessage());
            renderArgs.put("state","io_exception");
            //invalidXml("io_exception");            
        } catch(Exception e) {
            Logger.error("创建验证码失败(Exception)：",e);
            renderArgs.put("message",e.getMessage());
            renderArgs.put("state","other_exception");     
            //invalidXml("other_exception");
        }        
        renderTemplate("/Fetions/getVerify.xml");
    }
    
    // 创造Verfiy
    private static VerifyImage makeVerfiy(FetionClient client) throws IOException {
        VerifyImage vimg = client.fetchVerifyImage();
        File verifyImgFile = new File(Play.applicationPath.getAbsolutePath() + "\\public\\images\\fetion_verify\\"  + verifyImageFileName(vimg));
        FileOutputStream out = new FileOutputStream(verifyImgFile);    			  
        out.write(vimg.getImageData());
        out.close();        
        Logger.debug("确认码文件已成功保存在" + verifyImgFile.getAbsolutePath() + "id: " + vimg.getImageId());
        //throw new IOException("aaaaaaaaaaaaaa");  
        return vimg;
    }
    
    private static void sending(FetionClient client, String content, String mobile, String destMobile, String verifyImgId, String verifyCode) {        
        if(destMobile == null) {
          for(String c : content.split(SEPARATOR)) {
            Logger.debug("自己[" + mobile +"]给自己发");
            client.sendSMSMessageToSelf(new Message(c,Message.TYPE_PLAIN), null);
          }  
        } else {
          String[] contents = content.split(SEPARATOR);
          String[] destMobiles = destMobile.split(SEPARATOR);  
          for(int i = 0; i < contents.length; i ++) {       
            if(mobile.equals(destMobiles[i])) {
              Logger.debug("自己[" + mobile +"]给自己[" + destMobiles[i] + "]发");
              client.sendSMSMessageToSelf(new Message(contents[i],Message.TYPE_PLAIN), null);
            } else {
                Logger.debug("[" + mobile +"]给[" + destMobiles[i] + "]发");   
                try {                
                  // 是否是好友
                  client.findBuddyByMobile(new Long(destMobiles[i]),
                    new ActionEventListener() { 
                        public void fireEevent(ActionEvent event) {
                  				if(event.getEventType() == ActionEventType.SUCCESS) {
                  					Logger.debug("有这个好友！");                      				  
                  				} else {
                  				  Logger.debug("无此好友！");
                  				  renderArgs.put("message","不能发送给非好友");
                            renderArgs.put("state","NO_SUCH_FRIEND");    
                          }
                  			}
                  		}
                  );
                  if(renderArgs.get("state") == null) {                        
                    client.sendSMSMessage(new Long(destMobiles[i]),
                      new Message(contents[i],Message.TYPE_PLAIN),
                      null);
                  }
              	} catch(NumberFormatException nfe) {                  		  
                    renderArgs.put("message","不能发送给非好友");
                    renderArgs.put("state","NO_SUCH_FRIEND");  
                }                  
            }                
          }
        }                    
		    if(renderArgs.get("state") == null) {
		      Logger.debug("发送成功");
		      renderArgs.put("state","SUCCESS"); 
          renderArgs.put("message","短信发送成功");  
		    }
    }
    
    public static void friends(String mobile, String password, String verifyImgId,String verifyCode) {
        debugParams();
        Logger.debug("2. 准备从" + mobile + "取得好友列表");
        validateStateAndDoIt(mobile, password, null , null ,  verifyImgId, verifyCode, "getFriends");
        renderTemplate("/Fetions/friends.xml"); 
    }
    
    private static void getFriends(FetionClient client,String mobile, String password, String verifyImgId,String verifyCode) {
        Logger.debug("开始获取好友列表");
        Collection<Buddy> friends =  new Vector<Buddy>();
        for( Buddy buddy : client.getFetionStore().getBuddyList()) {
            if(buddy.getRelation() == Relation.BUDDY) {
                friends.add(buddy);  
            }            
        }
        Logger.debug("共有" + friends.size() + "个好友");
  	    if(renderArgs.get("state") == null) {
  	      Logger.debug("获取好友成功");
  	      renderArgs.put("friends",friends);
  	      renderArgs.put("state","SUCCESS"); 
          renderArgs.put("message","获取好友成功");  
  	    }      
    }
    
    private static void validateStateAndDoIt(String mobile, String password, String content,String destMobile, String verifyImgId,String verifyCode,String doIt) {
       if(isBlank(mobile)) {
            Logger.debug("3. mobile_requested");
            //invalidXml("mobile_requested");
            renderArgs.put("state","mobile_requested"); 
            renderArgs.put("message","手机号必填");
        } else if(isBlank(password)) {            
            //Logger.debug("3. password_requested");
            //invalidXml("password_requested");
            renderArgs.put("state","password_requested"); 
            renderArgs.put("message","密码不正确");
        } else{
            try {
                FetionClient client = new FetionClient(mobile, password);
                LoginState state;
                client.enableGroup(false);
                if(verifyCode == null) {
                    Logger.debug("开始");
                    state = client.syncLogin();
                } else {
                    Logger.debug("验证码登录");
                    VerifyImage img = new VerifyImage(verifyImgId,null);
        		        img.setVerifyCode(verifyCode);
                    state = client.syncLogin(Presence.ONLINE, img);
                }
                // 登陆成功
                
                if(state == LoginState.LOGIN_SUCCESS) {  
                    //Logger.debug();                              
                    Logger.debug("登陆成功 ...");
            		    if ( doIt.equals("sending")) {
            		      sending(client,content, mobile, destMobile, verifyImgId, verifyCode);
            		    } else if ( doIt.equals("getFriends")) {
            		      getFriends(client, mobile, password, verifyImgId, verifyCode);
            		    } else {
            		      Logger.error("未知的回调类型:" + doIt);
            		      renderArgs.put("message","回调错误");
                      renderArgs.put("state","CallBackExpcetion");
            		    }   
            		    // 打完收工
            		    client.logout();         		    
                } else if(state == LoginState.SSI_AUTH_FAIL) {
                    renderArgs.put("message","你输入的手机号或者密码不对");
                    renderArgs.put("state",state);
                    Logger.debug("你输入的手机号或者密码不对");
                    //invalidXml("SSI_AUTH_FAIL");
                } else if(state == LoginState.SSI_CONNECT_FAIL) {
                    renderArgs.put("message","SSI连接失败");
                    renderArgs.put("state",state);
                    Logger.debug("SSI连接失败");
                    //invalidXml("SSI_CONNECT_FAIL");
                } else if(state == LoginState.SIPC_CONNECT_FAIL) {
                    renderArgs.put("message","SIPC服务器连接失败");
                    renderArgs.put("state",state);
                    Logger.debug("SIPC服务器连接失败");
                    //invalidXml("SIPC_CONNECT_FAIL");
                } else if(state == LoginState.SIPC_AUTH_FAIL) {
                    renderArgs.put("message","SIPC验证失败");
                    renderArgs.put("state",state);
                    Logger.debug("SIPC验证失败");
                    //invalidXml("SIPC_CONNECT_FAIL");
                } else if(state == LoginState.SSI_NEED_VERIFY) { 
                    renderArgs.put("message","需要验证");
                    renderArgs.put("state",state);
                    Logger.debug("需要验证");
                    //invalidXml("SSI_NEED_VERIFY");
                } else if (state == LoginState.SSI_VERIFY_FAIL) {
                    renderArgs.put("message","验证码不正确");
                    renderArgs.put("state",state);
                    Logger.debug("验证码不正确");
                    //invalidXml("SSI_VERIFY_FAIL");
                } else if (state == LoginState.OHTER_ERROR) {
                    renderArgs.put("message","其他类型错误");
                    renderArgs.put("state",state);
                    Logger.debug("其他类型错误");
                } else {
                    renderArgs.put("message","其他类型错误");
                    renderArgs.put("state",state);
                    Logger.debug("其他类型错误");
                }
                
            } catch(IllegalStateException ise) {
                Logger.error("cmcc_mobile_requested:", ise);
                //invalidXml("cmcc_mobile_requested");
                renderArgs.put("state","cmcc_mobile_requested"); 
                renderArgs.put("message","手机号必须是中国移动的");                
            }            
        } 
    }
    
    private static String verifyImageFileName(VerifyImage verifyImg) {
        return verifyImg.getImageId() + "verify.png";
    }
    
    private static void debugParams() {
        Logger.debug("1. 看看都传了啥参数");
        Iterator keySet = params.all().keySet().iterator();
        while(keySet.hasNext())  {
          String key = (String)keySet.next();
          Logger.debug(key + " : " + (String)params.get(key));
        }
    }
}